Page({
  data: {
    userRole: 'student',
    hasCheckedIn: false, // 是否已签到
    hasCheckedOut: false, // 是否已签退
    location: '', // 当前位置
    locationData: {
      latitude: null,
      longitude: null,
      name: '',
      city: '',
      district: '',
      address: ''
    },
    currentTime: '', // 当前时间
    stats: { // 考勤统计
      normal: 0,
      late: 0,
      early: 0,
      absent: 0
    },
    
    // 学生课程列表
    studentCourses: [],
    selectedCourseIndex: 0,
    currentCourseId: null // 当前签到的课程ID
  },
  
  onLoad: function(options) {
    // 获取用户信息
    const userInfo = wx.getStorageSync('userInfo') || {};
    const token = wx.getStorageSync('token');

    // 设置用户角色
    this.setData({
      userRole: userInfo.role || 'student'
    });

    // 获取个人考勤统计
    this.fetchAttendanceStats();
    // 获取学生课程列表
    this.fetchStudentCourses();
    
    // 获取当前位置
    this.getLocation();
    
    // 更新当前时间
    this.updateCurrentTime();
    // 设置定时器，每分钟更新一次时间
    this.timeInterval = setInterval(() => {
      this.updateCurrentTime();
    }, 60000);
    
    // 检查今日是否已签到
    this.checkTodayAttendance();
  },
  
  onUnload: function() {
    // 清除定时器
    if (this.timeInterval) {
      clearInterval(this.timeInterval);
    }
  },
  
  // 更新当前时间
  updateCurrentTime: function() {
    const now = new Date();
    const hours = now.getHours().toString().padStart(2, '0');
    const minutes = now.getMinutes().toString().padStart(2, '0');
    this.setData({
      currentTime: `${hours}:${minutes}`
    });
  },
  
  
  // 获取位置信息
  getLocation: function() {
    const that = this;
    wx.showLoading({
      title: '获取位置中...',
    });
    
    // 使用腾讯地图IP定位API
    wx.request({
      url: 'https://apis.map.qq.com/ws/location/v1/ip',
      data: {
        key: 'E7IBZ-FOSW3-H6Z3U-OG4X4-CWTDH-QNBV4'
      },
      success: (res) => {
        if (res.data.status === 0 && res.data.result && res.data.result.location) {
          const location = res.data.result.location;
          
          that.setData({
            locationData: {
              latitude: location.lat,
              longitude: location.lng,
              name: '正在获取地址...'
            },
            location: '正在获取地址...'
          });
          
          // 获取位置名称
          that.getLocationName(location.lat, location.lng);
        } else {
          wx.hideLoading();
          wx.showModal({
            title: '提示',
            content: '获取位置失败，请稍后重试',
            showCancel: false
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showModal({
          title: '提示',
          content: '网络请求失败，请检查网络连接',
          showCancel: false
        });
      }
    });
  },
  
  // 添加获取位置名称的方法
  getLocationName: function(latitude, longitude) {
    const that = this;
    
    wx.request({
      url: 'https://apis.map.qq.com/ws/geocoder/v1/',
      data: {
        location: latitude + ',' + longitude,
        key: 'E7IBZ-FOSW3-H6Z3U-OG4X4-CWTDH-QNBV4',
        get_poi: 0
      },
      success: (res) => {
        wx.hideLoading();
        
        if (res.data.status === 0 && res.data.result) {
          const addressComponent = res.data.result.address_component;
          const formatted_addresses = res.data.result.formatted_addresses;
          const locationName = formatted_addresses ? formatted_addresses.recommend : res.data.result.address;
          
          that.setData({
            locationData: {
              ...that.data.locationData,
              name: locationName,
              city: addressComponent.city,
              district: addressComponent.district,
              address: res.data.result.address
            },
            location: locationName
          });
        }
      },
      fail: () => {
        wx.hideLoading();
      }
    });
  },
  
  // 刷新位置信息
  refreshLocation: function() {
    this.getLocation();
  },
  
  // 获取学生课程列表
  fetchStudentCourses: function() {
    const userInfo = wx.getStorageSync('userInfo');
    const token = wx.getStorageSync('token');
    
    if (!userInfo || !userInfo.userId) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }
    
    wx.request({
      url: 'http://localhost:3000/api/courses/student',
      method: 'GET',
      data: {
        userId: userInfo.userId
      },
      header: {
        'Authorization': 'Bearer ' + token
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.success) {
          this.setData({
            studentCourses: res.data.courses || []
          });
        } else {
          console.error('获取课程列表失败:', res);
          wx.showToast({
            title: '获取课程列表失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },
  
  // 处理课程选择变化
  handleCourseChange: function(e) {
    this.setData({
      selectedCourseIndex: e.detail.value
    });
  },
  
  // 检查今日是否已签到
  checkTodayAttendance: function() {
    const userInfo = wx.getStorageSync('userInfo');
    const token = wx.getStorageSync('token');
    
    if (!userInfo || !userInfo.userId) {
      return;
    }
    
    wx.request({
      url: 'http://localhost:3000/api/attendance/today', 
      method: 'GET',
      data: {
        userId: userInfo.userId
      },
      header: {
        'Authorization': 'Bearer ' + token
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.length > 0) {
          const attendance = res.data[0];
          this.setData({
            hasCheckedIn: true,
            checkinTime: attendance.checkInTime,
            hasCheckedOut: attendance.checkOutTime ? true : false,
            checkoutTime: attendance.checkOutTime || '',
            currentCourseId: attendance.courseId
          });
        }
      }
    });
  },
  
  // 获取考勤统计
// 获取考勤统计
fetchAttendanceStats: function() {
  const userInfo = wx.getStorageSync('userInfo');
  const token = wx.getStorageSync('token');
  
  if (!userInfo) {
    return;
  }
  
  // 使用正确的ID，可能是id而不是userId
  const userId = userInfo.id || userInfo.userId;
  
  console.log('获取考勤统计，用户ID:', userId);
  
  wx.request({
    url: 'http://localhost:3000/api/attendance/stats', 
    method: 'GET',
    data: {
      userId: userId,
      role: 'student'
    },
    header: {
      'Authorization': 'Bearer ' + token
    },
    success: (res) => {
      console.log('考勤统计结果:', res.data);
      if (res.statusCode === 200) {
        this.setData({
          stats: {
            normal: parseInt(res.data.normal) || 0,
            late: parseInt(res.data.late) || 0,
            early: parseInt(res.data.early) || 0,
            absent: parseInt(res.data.absent) || 0
          }
        });
      }
    },
    fail: (err) => {
      console.error('获取考勤统计失败:', err);
    }
  });
},
  
  // 签到方法
  checkIn: function() {
  // 获取用户信息
  const userInfo = wx.getStorageSync('userInfo') || {};
  const token = wx.getStorageSync('token');
  
  console.log('用户信息:', userInfo);
  
  // 检查是否有课程可选
  if (this.data.studentCourses.length === 0) {
      wx.showModal({
        title: '签到失败',
        content: '没有可签到的课程',
        showCancel: false
      });
      return;
    }
    
    // 获取选中的课程
    const selectedCourse = this.data.studentCourses[this.data.selectedCourseIndex];
    console.log('选中的课程:', selectedCourse);
    
    if (!selectedCourse || !selectedCourse.id) {
      wx.showModal({
        title: '签到失败',
        content: '请选择要签到的课程',
        showCancel: false
      });
      return;
    }
    
    // 显示加载提示
    wx.showLoading({
      title: '签到中...',
    });
    
    // 获取位置信息
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        const location = {
          latitude: res.latitude,
          longitude: res.longitude,
          accuracy: res.accuracy,
          timestamp: new Date().getTime()
        };
        
        // 先检查是否有活动的签到会话
        wx.request({
          url: 'http://localhost:3000/api/attendance/active-session', 
          method: 'GET',
          data: {
            userId: userInfo.userId || userInfo.id,
            courseId: selectedCourse.id,
            classId: userInfo.classId || selectedCourse.classId // 添加班级ID
          },
          header: {
            'Authorization': 'Bearer ' + token
          },
          success: (sessionRes) => {
            console.log('活动会话检查结果:', sessionRes.data);
            
            if (sessionRes.statusCode === 200 && sessionRes.data && sessionRes.data.sessionId) {
              // 有活动的签到会话，进行签到
              const sessionId = sessionRes.data.sessionId;
              
              wx.request({
                url: 'http://localhost:3000/api/attendance/checkin', // 修改这里：attendances -> attendance
                method: 'POST',
                data: {
                  userId: userInfo.userId || userInfo.id,
                  courseId: selectedCourse.id,
                  sessionId: sessionId,
                  location: location
                },
                header: {
                  'Authorization': 'Bearer ' + token,
                  'Content-Type': 'application/json'
                },
                success: (res) => {
                  wx.hideLoading();
                  console.log('签到结果:', res.data);
                  
                  if (res.statusCode === 201 || res.statusCode === 200) {
                    wx.showToast({
                      title: '签到成功',
                      icon: 'success'
                    });
                    
                    // 更新签到状态
                    this.setData({
                      hasCheckedIn: true,
                      checkinTime: res.data.checkinTime ? new Date(res.data.checkinTime).toLocaleTimeString() : new Date().toLocaleTimeString()
                    });
                    
                    // 刷新考勤统计
                    this.fetchAttendanceStats();
                  } else {
                    wx.showModal({
                      title: '签到失败',
                      content: res.data.message || '请稍后重试',
                      showCancel: false
                    });
                  }
                },
                fail: (err) => {
                  wx.hideLoading();
                  console.error('签到请求失败:', err);
                  wx.showModal({
                    title: '签到失败',
                    content: '网络错误，请稍后重试',
                    showCancel: false
                  });
                }
              });
            } else {
              wx.hideLoading();
              wx.showModal({
                title: '签到失败',
                content: '当前没有开放的签到会话',
                showCancel: false
              });
            }
          },
          fail: (err) => {
            wx.hideLoading();
            console.error('检查签到会话失败:', err);
            wx.showModal({
              title: '签到失败',
              content: '网络错误，请稍后重试',
              showCancel: false
            });
          }
        });
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('获取位置失败:', err);
        wx.showModal({
          title: '签到失败',
          content: '获取位置信息失败，请确保已授权位置权限',
          showCancel: false
        });
      }
    });
  },
  
  // 签退方法
  checkOut: function() {
    if (!this.data.locationData || !this.data.locationData.latitude) {
      wx.showToast({
        title: '位置信息未获取，请稍后再试',
        icon: 'none'
      });
      return;
    }
    
    if (!this.data.currentCourseId) {
      wx.showModal({
        title: '签退失败',
        content: '请先完成签到',
        showCancel: false
      });
      return;
    }
    
    wx.showLoading({
      title: '签退中...',
    });
    
    // 获取用户ID和令牌
    const userInfo = wx.getStorageSync('userInfo') || {};
    const userId = userInfo.userId || wx.getStorageSync('userId');
    const token = wx.getStorageSync('token');
    
    // 发送签退请求，包含完整的位置信息用于后端比对
    wx.request({
      url: 'http://localhost:3000/api/attendance/checkout',
      method: 'POST',
      data: {
        userId: userId,
        courseId: this.data.currentCourseId,
        location: {
          latitude: this.data.locationData.latitude,
          longitude: this.data.locationData.longitude,
          address: this.data.locationData.address || this.data.locationData.name,
          city: this.data.locationData.city,
          district: this.data.locationData.district,
          name: this.data.locationData.name
        },
        timestamp: new Date().getTime()
      },
      header: {
        'content-type': 'application/json',
        'Authorization': token ? `Bearer ${token}` : ''
      },
      success: (res) => {
        wx.hideLoading();
        
        // 添加对返回数据的检查
        if (!res.data) {
          wx.showModal({
            title: '签退失败',
            content: '服务器返回数据为空，请稍后重试',
            showCancel: false
          });
          return;
        }
        
        if (res.statusCode === 201 || res.statusCode === 200) {
          // 获取当前时间
          const now = new Date();
          const hours = now.getHours().toString().padStart(2, '0');
          const minutes = now.getMinutes().toString().padStart(2, '0');
          const checkoutTime = `${hours}:${minutes}`;
          
          this.setData({
            hasCheckedOut: true,
            checkoutTime: res.data.checkoutTime || checkoutTime
          });
          
          wx.showToast({
            title: '签退成功',
            icon: 'success'
          });
          
          // 更新考勤统计
          this.fetchAttendanceStats();
        } else {
          let errorMessage = '签退失败，请重试';
          if (res.data && res.data.message) {
            if (res.data.message.includes('超时')) {
              errorMessage = '签退已超时，请联系教师';
            } else if (res.data.message.includes('位置')) {
              errorMessage = '位置不在有效范围内，请确保在教室内签退';
            } else {
              errorMessage = res.data.message;
            }
          }
          
          wx.showModal({
            title: '签退失败',
            content: errorMessage,
            showCancel: false
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },
  
  // 格式化时间的辅助函数
  formatTime: function(date) {
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    return `${hours}:${minutes}`;
  },
  
  // 跳转到考勤记录页面
  navigateToKaoqinJilu: function() {
    wx.navigateTo({
      url: '../kaoqinjilu/kaoqinjilu'
    });
  }
});